package com.kzw.oa.system.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kzw.core.bean.Msg;
import com.kzw.core.util.web.ServletUtils;
import com.kzw.misc.utils.AppUtil;
import com.kzw.oa.system.model.SysConfig;
import com.kzw.oa.system.service.SysConfigService;

@Controller
@RequestMapping("/system/config/")
public class SysConfigAction {

	@Autowired
	private SysConfigService sysConfigService;

	/**
	 * 添加及保存操作
	 */
	@ResponseBody
	@RequestMapping("save")
	public Msg save(String typeKey, HttpServletRequest request) {
		Map<String, String> cnf = AppUtil.getSysConfig();
		// 从request中获取含属性前缀名的参数,构造去除前缀名后的参数Map.
		Map<String, Object> paramMap = ServletUtils.getParametersStartingWith(request, "cnf.");
		for (Entry<String, Object> entry : paramMap.entrySet()) {
			String key = entry.getKey();
			SysConfig conf = sysConfigService.findUniqueBy("configKey", key);
			if (conf == null) {
				conf = new SysConfig();
				conf.setConfigKey(key);
			}
			if (StringUtils.isNotBlank(typeKey)) {
				conf.setTypeKey(typeKey);
			}

			String val = entry.getValue() + "";
			conf.setDataValue(val);
			sysConfigService.saveOrUpdate(conf);

			cnf.remove(key);
			cnf.put(key, val);
		}

		// 更新系统配置的Map
		AppUtil.reloadSysConfig();

		return new Msg();
	}

	@ResponseBody
	@RequestMapping("find")
	public Msg find(String typeKey) {
		List<SysConfig> list;
		if (StringUtils.isNotBlank(typeKey)) {
			String hql = "from SysConfig where typeKey=?";
			list = sysConfigService.findByHQL(hql, typeKey);
		} else {
			String hql = "from SysConfig";
			list = sysConfigService.findByHQL(hql);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		for (SysConfig cfg : list) {
			map.put(cfg.getConfigKey(), cfg.getDataValue());
		}

		return new Msg(true, 0, "配置信息", map);
	}

}
